package com.czy.moudle.exception.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.czy.moudle.exception.domain.ExceptionConfig;
import com.czy.moudle.exception.domain.enums.Level;
import com.czy.moudle.exception.service.ExceptionConfigService;
import com.czy.util.FileContentUtils;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.collections.MapUtils;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.stereotype.Service;
import org.springframework.util.FileSystemUtils;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/***
 * 异常配置服务类：文件配置
 *
 * @author 陈致远
 * @date 2016/8/12
 */
@Service("fileExceptionConfigServiceImpl")
public class FileExceptionConfigServiceImpl implements ExceptionConfigService {
    @Override
    public Map<String, ExceptionConfig> loadExceptinConfigList() {
        /**
         * 懒加载
         */
        if (configs == null || configs.size() == 0) {
            Resource exJson = new ClassPathResource(EXC_CONF_JSON_FILE);

            InputStream inputStream = null;

            try {
                inputStream = exJson.getInputStream();

                String content = FileContentUtils.inputStream2String(inputStream);
//                content = new String(content.getBytes(), "GBK");

                JSONArray array = JSON.parseArray(content);

                for (int i = 0; i < array.size(); i++) {
                    Map<String, String> map = (Map<String, String>) array.get(i);
                    configs.put(map.get("errKey"), map2ExceptionCfg(map));
                }

            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                if (null != inputStream) {
                    try {
                        inputStream.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        }

        return configs;
    }

    private ExceptionConfig map2ExceptionCfg(Map<String, String> map) {
        ExceptionConfig config = new ExceptionConfig();
        config.setErrKey(map.get("errKey"));
        config.setContent(map.get("content"));
        config.setErrCode(MapUtils.getLong(map, "errCode"));
        config.setErrInfo(map.get("errInfo"));
        config.setErrLevel(Level.getByName(map.get("errLevel")));
        return config;
    }
}
